/*
 * @lc app=leetcode.cn id=807 lang=cpp
 *
 * [807] 保持城市天际线
 */

// @lc code=start
class Solution
{
public:
  int maxIncreaseKeepingSkyline(vector<vector<int>>& grid)
  {
    int ans = 0;
    int m = grid.size();
    int n = grid[0].size();
    vector<int> row_max(n);
    vector<int> col_max(m);

    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        if (grid[i][j] > row_max[i])
          row_max[i] = grid[i][j];
        if (grid[i][j] > col_max[j])
          col_max[j] = grid[i][j];
      }
    }

    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j)
        ans += min(row_max[i], col_max[j]) - grid[i][j];
    }

    return ans;
  }
};
// @lc code=end
